import Foundation
import CoreImage
import Metal
import MetalKit

// MARK: - Filter Model
struct YCFilter {
    // 滤镜类型
    let type: FilterType
    // 滤镜名称
    let name: String
    // 协议
    let effect: FilterEffect
    // 参数
    var parameters: FilterParameters
    
    init(type: FilterType, name: String, effect: FilterEffect, parameters: FilterParameters = FilterParameters()) {
        self.type = type
        self.name = name
        self.effect = effect
        self.parameters = parameters
    }
}

// MARK: - Filter Type
enum FilterType: String, CaseIterable {
    case none = "原图"
    case fujiNC = "富士NC"
    case realistic = "写实"
    case breeze = "微风"
    case noir = "黑白"
    case vintage = "复古"
    case fade = "褪色"
    case instant = "怀旧"
    case dream = "梦幻"
    case dramatic = "戏剧"
    case chrome = "铬黄"
    case tonal = "冷调2"
    case sepia = "复古2"
    case hasselblad = "哈苏"
    case hasselbladBW = "哈苏黑白"
    case hasselbladVintage = "哈苏复古"
    case classicFilm = "胶片经典"
    case filmEra = "胶片年代"
    case fx7 = "fx7"
    
    // 🆕 新增 LUT 滤镜（示例）
    // case leicaVivid = "徕卡生动"
    // case kodakPortra = "柯达Portra"
    // case cinematicWarm = "电影暖色"
}

// MARK: - Filter Parameters
struct FilterParameters {
    var brightness: Float = 0.0     // 亮度: -1.0 到 1.0
    var contrast: Float = 1.0       // 对比度: 0.0 到 4.0
    var saturation: Float = 1.0     // 饱和度: 0.0 到 2.0
    var temperature: Float = 6500   // 色温: 4000(冷) 到 9000(暖)
    var tint: Float = 0.0           // 色调: -150.0 到 150.0
    var intensity: Float = 1.0      // 效果强度: 0.0 到 1.0
    var radius: Float = 1.0         // 效果范围: 0.0 到 2.0
    
    // 预设参数集
    static let fujiNC = FilterParameters(
        brightness: -0.03,    // 轻微降低亮度
        contrast: 1.12,       // 适中的对比度
        saturation: 0.95,     // 轻微降低饱和度
        temperature: 6300     // 偏冷色调
    )
    
    static let realistic = FilterParameters(
        brightness: 0.0,
        contrast: 1.1,
        saturation: 1.0,
        temperature: 6500
    )
    
    static let breeze = FilterParameters(
        brightness: 0.02,
        contrast: 1.05,
        saturation: 0.92,
        temperature: 6800
    )
    
    static let dream = FilterParameters(
        brightness: 0.1,
        contrast: 0.9,
        saturation: 1.4,
        radius: 3.0
    )
    
    static let dramatic = FilterParameters(
        brightness: 0.0,
        contrast: 1.5,
        saturation: 0.8,
        intensity: 1.0
    )
}

// MARK: - Filter Effect Protocol
protocol FilterEffect {
    var filterName: String? { get }
    func apply(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage?
    func supportsMetalAcceleration() -> Bool
    func applyMetal(to image: CIImage, with parameters: FilterParameters, device: MTLDevice, commandQueue: MTLCommandQueue) -> CIImage?
}

// MARK: - Base Filter Effect
class BaseFilterEffect: FilterEffect {
    var filterName: String? { return nil }
    
    func apply(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage? {
        return image
    }
    
    func supportsMetalAcceleration() -> Bool {
        return false
    }
    
    func applyMetal(to image: CIImage, with parameters: FilterParameters, device: MTLDevice, commandQueue: MTLCommandQueue) -> CIImage? {
        return nil
    }
}

// MARK: - LUT Filter Effect
class LUTFilterEffect: BaseFilterEffect {
    private let lutName: String
    private let intensity: Float
    private let lutData: Data?
    
    init(lutName: String, intensity: Float = 1.0) {
        self.lutName = lutName
        self.intensity = intensity
        self.lutData = LUTFilterEffect.loadLUTData(from: lutName)
        super.init()
    }
    
    override func apply(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage? {
        guard let lutFilter = CIFilter(name: "CIColorCubeWithColorSpace"),
              let lutData = self.lutData else { 
            return image 
        }
        
        lutFilter.setValue(image, forKey: kCIInputImageKey)
        lutFilter.setValue(lutData, forKey: "inputCubeData")
        lutFilter.setValue(64, forKey: "inputCubeDimension")
        lutFilter.setValue(CGColorSpaceCreateDeviceRGB(), forKey: "inputColorSpace")
        
        if let output = lutFilter.outputImage {
            if parameters.intensity < 1.0 {
                return blendWithOriginal(output, original: image, intensity: parameters.intensity)
            }
            return output
        }
        
        return image
    }
    
    private static func loadLUTData(from fileName: String) -> Data? {
        // 获取当前 Bundle
        let bundle = Bundle.main
        
        // 尝试多种路径格式
        let possiblePaths = [
            fileName,                    // 直接使用文件名
            "Camera/Lut/\(fileName)",   // 相对于项目根目录的路径
            "Lut/\(fileName)",          // Lut 目录
            "\(fileName.replacingOccurrences(of: "_lut", with: ""))" // 尝试不同的文件名格式
        ]
        
        // 查找文件路径
        guard let finalPath = possiblePaths.lazy
            .compactMap({ bundle.path(forResource: $0.replacingOccurrences(of: ".cube", with: ""),
                                    ofType: "cube") })
            .first else {
            print("未找到LUT文件: \(fileName)")
            return nil
        }
        
        // 读取文件内容
        guard let cubeContent = try? String(contentsOfFile: finalPath, encoding: .utf8) else {
            print("无法读取LUT文件内容: \(fileName)")
            return nil
        }
        
        // 解析 LUT 数据
        var colorData = [Float]()
        colorData.reserveCapacity(64 * 64 * 64 * 4) // 预分配内存
        
        let lines = cubeContent.components(separatedBy: .newlines)
        
        // 使用更高效的解析方法
        for line in lines {
            let trimmed = line.trimmingCharacters(in: .whitespaces)
            
            // 跳过注释和头部信息
            if trimmed.isEmpty || trimmed.hasPrefix("#") ||
               trimmed.hasPrefix("LUT_3D_SIZE") ||
               trimmed.hasPrefix("DOMAIN") {
                continue
            }
            
            // 快速解析颜色值
            let components = trimmed.split(separator: " ").compactMap { Float($0) }
            if components.count == 3 {
                colorData.append(contentsOf: components)
                colorData.append(1.0)
            }
        }
        
        // 创建 LUT 数据
        return Data(bytes: &colorData, count: colorData.count * MemoryLayout<Float>.size)
    }
    
    private func blendWithOriginal(_ filtered: CIImage, original: CIImage, intensity: Float) -> CIImage? {
        guard let blendFilter = CIFilter(name: "CISourceOverCompositing") else { return filtered }
        
        if let alphaFilter = CIFilter(name: "CIColorMatrix") {
            alphaFilter.setValue(filtered, forKey: kCIInputImageKey)
            alphaFilter.setValue(CIVector(x: 1, y: 0, z: 0, w: 0), forKey: "inputRVector")
            alphaFilter.setValue(CIVector(x: 0, y: 1, z: 0, w: 0), forKey: "inputGVector")
            alphaFilter.setValue(CIVector(x: 0, y: 0, z: 1, w: 0), forKey: "inputBVector")
            alphaFilter.setValue(CIVector(x: 0, y: 0, z: 0, w: CGFloat(intensity)), forKey: "inputAVector")
            
            if let alphaOutput = alphaFilter.outputImage {
                blendFilter.setValue(alphaOutput, forKey: kCIInputImageKey)
                blendFilter.setValue(original, forKey: kCIInputBackgroundImageKey)
                return blendFilter.outputImage
            }
        }
        
        return filtered
    }
}

// MARK: - Basic Filter Effect
class BasicFilterEffect: BaseFilterEffect {
    
    private let ciFilterName: String
    
    init(ciFilterName: String) {
        self.ciFilterName = ciFilterName
        super.init()
    }
    
    override var filterName: String? {
        return ciFilterName
    }
    
    override func apply(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage? {
        guard let filter = CIFilter(name: ciFilterName) else { return image }
        
        filter.setValue(image, forKey: kCIInputImageKey)
        
        // Apply parameters based on filter type
        if ciFilterName == "CIColorControls" {
            filter.setValue(parameters.brightness, forKey: kCIInputBrightnessKey)
            filter.setValue(parameters.contrast, forKey: kCIInputContrastKey)
            filter.setValue(parameters.saturation, forKey: kCIInputSaturationKey)
        } else if ciFilterName == "CISepiaTone" {
            filter.setValue(parameters.intensity, forKey: kCIInputIntensityKey)
        }
        
        return filter.outputImage ?? image
    }
    
    override func supportsMetalAcceleration() -> Bool {
        return true
    }
}

// MARK: - Complex Filter Effect
class ComplexFilterEffect: BaseFilterEffect {
    private let filterType: FilterType
    
    init(filterType: FilterType) {
        self.filterType = filterType
        super.init()
    }
    
    override func apply(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage? {
        var result = image
        
        switch filterType {
        case .realistic:
            result = applyRealisticEffect(to: image, with: parameters, context: context)
        case .breeze:
            result = applyBreezeEffect(to: image, with: parameters, context: context)
        case .filmEra:
            result = applyFilmEraEffect(to: image, with: parameters, context: context)
        case .hasselblad:
            result = applyHasselbladEffect(to: image, with: parameters, context: context)
        // Add more complex filter implementations
        default:
            break
        }
        
        return result
    }
    
    private func applyRealisticEffect(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage {
        
        guard let filter = CIFilter(name: "CIColorControls") else { return image }
        
        filter.setValue(image, forKey: kCIInputImageKey)
        // 写实滤镜：自然的色彩还原，适度提升对比度和清晰度
        filter.setValue(1.08, forKey: kCIInputContrastKey)     // 轻微提升对比度，避免过度
        filter.setValue(0.98, forKey: kCIInputSaturationKey)   // 轻微降低饱和度，更自然
        filter.setValue(-0.02, forKey: kCIInputBrightnessKey)  // 稍微降低亮度，避免过曝
        
        guard let outputImage = filter.outputImage else { return image }
        
        // 添加自然色调
        if let toneFilter = CIFilter(name: "CIToneCurve") {
            toneFilter.setValue(outputImage, forKey: kCIInputImageKey)
            // 优化色调曲线，增强细节层次
            toneFilter.setValue(CIVector(x: 0.0, y: 0.0), forKey: "inputPoint0")
            toneFilter.setValue(CIVector(x: 0.25, y: 0.23), forKey: "inputPoint1")  // 轻微提升暗部
            toneFilter.setValue(CIVector(x: 0.5, y: 0.5), forKey: "inputPoint2")    // 保持中间调中性
            toneFilter.setValue(CIVector(x: 0.75, y: 0.77), forKey: "inputPoint3")  // 轻微压制高光
            toneFilter.setValue(CIVector(x: 1.0, y: 0.98), forKey: "inputPoint4")   // 保留高光细节
            
            guard let toneOutput = toneFilter.outputImage else { return outputImage }
            
            // 添加高光阴影精细调整
            if let highlightFilter = CIFilter(name: "CIHighlightShadowAdjust") {
                highlightFilter.setValue(toneOutput, forKey: kCIInputImageKey)
                highlightFilter.setValue(0.95, forKey: "inputHighlightAmount")  // 轻微压制高光
                highlightFilter.setValue(1.05, forKey: "inputShadowAmount")     // 轻微提升阴影
                
                guard let adjustedOutput = highlightFilter.outputImage else { return toneOutput }
                // 添加适度锐化，增强细节
                if let sharpenFilter = CIFilter(name: "CIUnsharpMask") {
                    sharpenFilter.setValue(adjustedOutput, forKey: kCIInputImageKey)
                    sharpenFilter.setValue(0.5, forKey: "inputRadius")      // 降低锐化范围，更自然
                    sharpenFilter.setValue(0.3, forKey: "inputIntensity")   // 降低锐化强度，避免过度
                    
                    guard let sharpenOutput = sharpenFilter.outputImage else { return adjustedOutput }
                    
                    // 最终的颜色平衡调整
                    if let colorBalanceFilter = CIFilter(name: "CIColorControls") {
                        colorBalanceFilter.setValue(sharpenOutput, forKey: kCIInputImageKey)
                        colorBalanceFilter.setValue(0.98, forKey: kCIInputSaturationKey)  // 最终微调饱和度
                        colorBalanceFilter.setValue(1.02, forKey: kCIInputContrastKey)    // 最终微调对比度
                        
                        return colorBalanceFilter.outputImage ?? sharpenOutput
                    }
                    return sharpenOutput
                }
                return adjustedOutput
            }
            return toneOutput
        }
        return outputImage
    }
    
    private func applyBreezeEffect(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage {
        
        guard let filter = CIFilter(name: "CIColorControls") else { return image }
        
        filter.setValue(image, forKey: kCIInputImageKey)
        // 微风滤镜：自然清新，层次分明，细节丰富
        filter.setValue(1.05, forKey: kCIInputContrastKey)    // 增加对比度
        filter.setValue(0.92, forKey: kCIInputSaturationKey)  // 保持适度饱和度
        filter.setValue(0.02, forKey: kCIInputBrightnessKey)  // 降低亮度
        
        guard let outputImage = filter.outputImage else { return image }
        
        // 添加温暖色调
        if let temperatureFilter = CIFilter(name: "CITemperatureAndTint") {
            temperatureFilter.setValue(outputImage, forKey: kCIInputImageKey)
            temperatureFilter.setValue(CIVector(x: 6800, y: 0), forKey: "inputNeutral")      // 温暖色调
            temperatureFilter.setValue(CIVector(x: 6500, y: 0), forKey: "inputTargetNeutral")
            
            guard let warmOutput = temperatureFilter.outputImage else { return outputImage }
            
            // 添加锐化效果
            if let sharpenFilter = CIFilter(name: "CIUnsharpMask") {
                sharpenFilter.setValue(warmOutput, forKey: kCIInputImageKey)
                sharpenFilter.setValue(0.6, forKey: "inputRadius")     // 保持锐化范围
                sharpenFilter.setValue(0.4, forKey: "inputIntensity")  // 保持锐化强度
                
                guard let sharpenOutput = sharpenFilter.outputImage else { return warmOutput }
                
                // 添加高光和阴影调整
                if let highlightFilter = CIFilter(name: "CIHighlightShadowAdjust") {
                    highlightFilter.setValue(sharpenOutput, forKey: kCIInputImageKey)
                    highlightFilter.setValue(0.95, forKey: "inputHighlightAmount")  // 降低高光
                    highlightFilter.setValue(0.85, forKey: "inputShadowAmount")     // 加深阴影
                    
                    guard let adjustedOutput = highlightFilter.outputImage else { return sharpenOutput }
                    // 添加色调曲线调整
                    if let curveFilter = CIFilter(name: "CIToneCurve") {
                        curveFilter.setValue(adjustedOutput, forKey: kCIInputImageKey)
                        // 优化的色调曲线，增加暗部层次，控制高光
                        curveFilter.setValue(CIVector(x: 0.0, y: 0.0), forKey: "inputPoint0")
                        curveFilter.setValue(CIVector(x: 0.25, y: 0.22), forKey: "inputPoint1")
                        curveFilter.setValue(CIVector(x: 0.5, y: 0.48), forKey: "inputPoint2")
                        curveFilter.setValue(CIVector(x: 0.75, y: 0.72), forKey: "inputPoint3")
                        curveFilter.setValue(CIVector(x: 1.0, y: 0.95), forKey: "inputPoint4")
                        
                        guard let curveOutput = curveFilter.outputImage else { return adjustedOutput }
                        
                        // 最后的细节增强
                        if let detailFilter = CIFilter(name: "CIColorControls") {
                            detailFilter.setValue(curveOutput, forKey: kCIInputImageKey)
                            detailFilter.setValue(1.05, forKey: kCIInputContrastKey)  // 轻微提升对比度
                            return detailFilter.outputImage ?? curveOutput
                        }
                        return curveOutput
                    }
                    return adjustedOutput
                }
                return sharpenOutput
            }
            return warmOutput
        }
        return outputImage
    }
    
    private func applyFilmEraEffect(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage {
        // Implement film era effect
        // ... (Keep existing film era implementation)
        // 胶片年代滤镜：完美还原经典胶片质感，增强50%胶片效果
        
        // 第一步：基础色彩校正 - 优化色彩基调
        guard let colorFilter = CIFilter(name: "CIColorControls") else { return image }
        colorFilter.setValue(image, forKey: kCIInputImageKey)
        colorFilter.setValue(1.15, forKey: kCIInputContrastKey)    // 增加对比度，强化层次感
        colorFilter.setValue(0.75, forKey: kCIInputSaturationKey)  // 降低饱和度，更接近胶片
        colorFilter.setValue(-0.05, forKey: kCIInputBrightnessKey) // 稍微降低亮度
        
        guard let baseOutput = colorFilter.outputImage else { return image }
        
        // 第二步：增强的柔焦效果，模拟胶片的柔和感
        guard let gaussianBlur = CIFilter(name: "CIGaussianBlur") else { return baseOutput }
        gaussianBlur.setValue(baseOutput, forKey: kCIInputImageKey)
        gaussianBlur.setValue(1.2, forKey: "inputRadius")  // 增加柔焦效果
        
        guard let blurOutput = gaussianBlur.outputImage else { return baseOutput }
        
        // 关键修复：裁剪模糊图像到原图精确边界，防止extent扩展
        guard let blurCrop = CIFilter(name: "CICrop") else { return baseOutput }
        blurCrop.setValue(blurOutput, forKey: kCIInputImageKey)
        blurCrop.setValue(CIVector(cgRect: image.extent), forKey: "inputRectangle")
        
        guard let croppedBlur = blurCrop.outputImage else { return baseOutput }
        
        // 第三步：智能混合原始图像和柔焦图像
        guard let blendFilter = CIFilter(name: "CISourceOverCompositing") else { return croppedBlur }
        blendFilter.setValue(croppedBlur, forKey: kCIInputImageKey)
        blendFilter.setValue(baseOutput, forKey: kCIInputBackgroundImageKey)
        
        guard let blendOutput = blendFilter.outputImage else { return croppedBlur }
        
        // 第四步：增强的色彩矩阵调整，优化胶片色彩特性
        guard let matrixFilter = CIFilter(name: "CIColorMatrix") else { return blendOutput }
        matrixFilter.setValue(blendOutput, forKey: kCIInputImageKey)
        // 红色通道：增强红色的层次感
        matrixFilter.setValue(CIVector(x: 1.15, y: 0.0, z: 0.0, w: 0), forKey: "inputRVector")
        // 绿色通道：优化绿色通道，增加自然度
        matrixFilter.setValue(CIVector(x: -0.08, y: 1.05, z: 0.0, w: 0), forKey: "inputGVector")
        // 蓝色通道：调整蓝色，优化整体色调
        matrixFilter.setValue(CIVector(x: 0.0, y: -0.05, z: 0.95, w: 0), forKey: "inputBVector")

        guard let colorMatrixOutput = matrixFilter.outputImage else { return blendOutput }
        
        // 第五步：增强50%的胶片颗粒感 - 精确控制边界
        guard let noiseFilter = CIFilter(name: "CIRandomGenerator") else { return colorMatrixOutput }
        guard let noiseImage = noiseFilter.outputImage else { return colorMatrixOutput }
        
        // 关键：直接裁剪噪点到原图尺寸，不要扩展
        guard let noiseCropFilter = CIFilter(name: "CICrop") else { return colorMatrixOutput }
        noiseCropFilter.setValue(noiseImage, forKey: kCIInputImageKey)
        noiseCropFilter.setValue(CIVector(cgRect: image.extent), forKey: "inputRectangle")
        
        guard let croppedNoise = noiseCropFilter.outputImage else { return colorMatrixOutput }
        
        // 优化颗粒效果
        guard let grainBlur = CIFilter(name: "CIGaussianBlur") else { return colorMatrixOutput }
        grainBlur.setValue(croppedNoise, forKey: kCIInputImageKey)
        grainBlur.setValue(0.8, forKey: "inputRadius")  // 增加颗粒大小
        
        guard let blurredGrain = grainBlur.outputImage else { return colorMatrixOutput }
        
        // 再次精确裁剪，确保模糊后的噪点不超出边界
        guard let grainCropFilter = CIFilter(name: "CICrop") else { return colorMatrixOutput }
        grainCropFilter.setValue(blurredGrain, forKey: kCIInputImageKey)
        grainCropFilter.setValue(CIVector(cgRect: image.extent), forKey: "inputRectangle")
        
        guard let croppedGrain = grainCropFilter.outputImage else { return colorMatrixOutput }
        
        // 增强颗粒感特性
        guard let grainMatrix = CIFilter(name: "CIColorMatrix") else { return colorMatrixOutput }
        grainMatrix.setValue(croppedGrain, forKey: kCIInputImageKey)
        grainMatrix.setValue(CIVector(x: 1.2, y: 0, z: 0, w: 0), forKey: "inputRVector")
        grainMatrix.setValue(CIVector(x: 0, y: 1.2, z: 0, w: 0), forKey: "inputGVector")
        grainMatrix.setValue(CIVector(x: 0, y: 0, z: 1.2, w: 0), forKey: "inputBVector")
        grainMatrix.setValue(CIVector(x: 0, y: 0, z: 0, w: 0.12), forKey: "inputAVector") // 增强50%颗粒感
        
        guard let adjustedGrain = grainMatrix.outputImage else { return colorMatrixOutput }
        
        // 修复：使用不同的混合模式防止边缘问题
        guard let grainComposite = CIFilter(name: "CISourceOverCompositing") else { return colorMatrixOutput }
        grainComposite.setValue(adjustedGrain, forKey: kCIInputImageKey)
        grainComposite.setValue(colorMatrixOutput, forKey: kCIInputBackgroundImageKey)
        
        guard let grainOutput = grainComposite.outputImage else { return colorMatrixOutput }

        // 第六步：优化的色调曲线调整
        guard let curveFilter = CIFilter(name: "CIToneCurve") else { return grainOutput }
        curveFilter.setValue(grainOutput, forKey: kCIInputImageKey)
        // 优化色调曲线，增强胶片特性
        curveFilter.setValue(CIVector(x: 0.0, y: 0.12), forKey: "inputPoint0")   // 加深黑场
        curveFilter.setValue(CIVector(x: 0.25, y: 0.32), forKey: "inputPoint1")  // 提升暗部细节
        curveFilter.setValue(CIVector(x: 0.5, y: 0.58), forKey: "inputPoint2")   // 优化中间调
        curveFilter.setValue(CIVector(x: 0.75, y: 0.80), forKey: "inputPoint3")  // 控制高光过渡
        curveFilter.setValue(CIVector(x: 1.0, y: 0.90), forKey: "inputPoint4")   // 压制极限高光
        
        guard let curveOutput = curveFilter.outputImage else { return grainOutput }
        
        // 第七步：增强的经典暗角效果 - 确保暗角不会产生边缘问题
        guard let vignetteFilter = CIFilter(name: "CIVignette") else { return curveOutput }
        vignetteFilter.setValue(curveOutput, forKey: kCIInputImageKey)
        vignetteFilter.setValue(0.45, forKey: kCIInputIntensityKey)  // 增强暗角效果
        vignetteFilter.setValue(1.6, forKey: kCIInputRadiusKey)      // 扩大暗角范围
        
        guard let vignetteOutput = vignetteFilter.outputImage else { return curveOutput }
        
        // 第八步：最终色彩平衡和微调
        guard let finalFilter = CIFilter(name: "CIColorControls") else { return vignetteOutput }
        finalFilter.setValue(vignetteOutput, forKey: kCIInputImageKey)
        finalFilter.setValue(0.85, forKey: kCIInputSaturationKey)  // 进一步降低饱和度
        finalFilter.setValue(1.12, forKey: kCIInputContrastKey)    // 微调最终对比度
        finalFilter.setValue(-0.02, forKey: kCIInputBrightnessKey) // 微调最终亮度
        
        // 第九步：添加轻微的色温调整
        guard let temperatureFilter = CIFilter(name: "CITemperatureAndTint"),
              let finalOutput = finalFilter.outputImage else { return vignetteOutput }
        
        temperatureFilter.setValue(finalOutput, forKey: kCIInputImageKey)
        temperatureFilter.setValue(CIVector(x: 6800, y: 0), forKey: "inputNeutral")  // 添加轻微暖调
        temperatureFilter.setValue(CIVector(x: 6500, y: 0), forKey: "inputTargetNeutral")
        
        let tempOutput = temperatureFilter.outputImage ?? finalOutput
        
        // 最终修复：精确裁剪到原始图像边界，避免任何边缘扩展
        // 使用 CICrop 确保输出图像的 extent 与输入完全一致
        guard let finalCropFilter = CIFilter(name: "CICrop") else { return tempOutput }
        finalCropFilter.setValue(tempOutput, forKey: kCIInputImageKey)
        // 关键：使用原始图像的精确 extent，不做任何 inset
        finalCropFilter.setValue(CIVector(cgRect: image.extent), forKey: "inputRectangle")
        
        return finalCropFilter.outputImage ?? tempOutput
    }
    
    private func applyHasselbladEffect(to image: CIImage, with parameters: FilterParameters, context: CIContext) -> CIImage {
        
        // 哈苏经典色彩效果
        guard let filter = CIFilter(name: "CIColorControls") else { return image }
        
        filter.setValue(image, forKey: kCIInputImageKey)
        // 1. 提高对比度和细节
        filter.setValue(1.1, forKey: kCIInputContrastKey)
        // 2. 轻微提升饱和度
        filter.setValue(1.15, forKey: kCIInputSaturationKey)
        // 3. 调整亮度
        filter.setValue(0.02, forKey: kCIInputBrightnessKey)
        
        guard let outputImage = filter.outputImage else { return image }
        
        // 4. 添加色调映射
        if let curveFilter = CIFilter(name: "CIToneCurve") {
            curveFilter.setValue(outputImage, forKey: kCIInputImageKey)
            // 调整色调曲线以增强中间调和高光
            curveFilter.setValue(CIVector(x: 0.0, y: 0.0), forKey: "inputPoint0")
            curveFilter.setValue(CIVector(x: 0.25, y: 0.2), forKey: "inputPoint1")
            curveFilter.setValue(CIVector(x: 0.5, y: 0.5), forKey: "inputPoint2")
            curveFilter.setValue(CIVector(x: 0.75, y: 0.8), forKey: "inputPoint3")
            curveFilter.setValue(CIVector(x: 1.0, y: 1.0), forKey: "inputPoint4")
            
            guard let curveOutput = curveFilter.outputImage else { return outputImage }
            
            // 5. 添加轻微锐化
            if let sharpenFilter = CIFilter(name: "CIUnsharpMask") {
                sharpenFilter.setValue(curveOutput, forKey: kCIInputImageKey)
                sharpenFilter.setValue(0.7, forKey: "inputRadius")
                sharpenFilter.setValue(0.7, forKey: "inputIntensity")
                return sharpenFilter.outputImage ?? curveOutput
            }
            return curveOutput
        }
        return outputImage
    }
} 
